#ifndef _PTHREAD_H_
#define _PTHREAD_H_

#include <iostream>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include<functional>
#include"Log.hpp"
using namespace std;
using namespace LogModule;
namespace PthreadModel
{
   
    static uint32_t number = 1;

    class pthread
    {
         using func_t=function<void()>;
    private:
        void EnableDetach()
        {
            _isdetach = true;
        }
    public:
        pthread(func_t func)
            : _tid(0), _isrunning(false), _isdetach(false),_func(func)
        {
            _name = "pthread-" + std::to_string(number++);
        }

        void Detach()
        {
            if ( _isdetach)
                return;
            if(_isrunning)
            {
                pthread_detach(_tid);
            }
            EnableDetach();  
        }
       

        void EnableRunning()
        {
            _isrunning = true;
        }

        static void *Rountine(void* args)
        {
            pthread* self=static_cast<pthread*>(args);
            self->EnableRunning(); 
            if(self->_isdetach)
            {
                self->Detach();
            }
            pthread_setname_np(self->_tid, self->_name.c_str());
            self->_func();
            return nullptr;
        }
        bool start()
        {
            int n = pthread_create(&_tid, nullptr, Rountine, this);
            if (n != 0)
            {
              
                return false;
            }
            
            return true;
        }
        bool Stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    std::cout << "pthread cancel error:" << std::endl;
                    return false;
                }
            }
            return true;
        }
        bool Join()
        {
            int n=pthread_join(_tid,nullptr);
            if(n!=0)
            {
                LOG(LogLevel::DEBUG) << "Join线程失败";
            }
            else{
                LOG(LogLevel::DEBUG) << "Join线程成功";
            }
            return true;
        }
        string Name()
        {
            return _name;
        }
        ~pthread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isrunning;
        bool _isdetach;
        func_t _func;
    };

};

#endif